package id.co.shuba.spamobile.activities;

import java.util.HashMap;

import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.CustomSessionApplication;
import id.co.shuba.spamobile.LogoutReceiver;
import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.Sessions;
import id.co.shuba.spamobile.R.layout;
import id.co.shuba.spamobile.R.menu;
import id.co.shuba.spamobile.services.WebServiceHelper;
import id.co.shuba.spamobile.task.BaseProgressTask;
import id.co.shuba.spamobile.task.DownloadUpdateTask;
import id.co.shuba.spamobile.task.DownloadUpdateV2Task;
import id.co.shuba.spamobile.task.LogoutTask;
import id.co.shuba.spamobile.util.Base64;
import id.co.shuba.spamobile.util.Str;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;

public class UpdateActivity extends SherlockActivity {
	private DownloadUpdateV2Task _task;
	private LogoutReceiver logoutReceiver;	
	private LogoutTask _logoutTask;

	private void setUpLogoutReceiver() {
		IntentFilter intentFilter = new IntentFilter();
	    intentFilter.addAction("id.co.shuba.spamobile.ACTION_LOGOUT");
	    logoutReceiver = new LogoutReceiver(this);
	    registerReceiver(logoutReceiver, intentFilter);
	}
	
	@Override
	public void onUserInteraction() {		
		super.onUserInteraction();
		((CustomSessionApplication) getApplication()).touch();
		if (App.DEBUG) {			
			Log.d("User Interaction", "User interaction to "+this.toString());			
		}
	}
	
	@Override
	protected void onDestroy() {
		unregisterReceiver(logoutReceiver);
		super.onDestroy();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update);				
		setUpLogoutReceiver();
		
		String url = getIntent().getStringExtra("URL");
		String version = getIntent().getStringExtra("VERSION");
		String size = getIntent().getStringExtra("SIZE");
		long checksum = getIntent().getLongExtra("CHECKSUM", 0);
		
		String message = String.format("Downloading version %s (%s)", version, size);
		
		TextView txtMessage = (TextView) findViewById(R.id.txtMessage);
		txtMessage.setText(message);
		TextView txtStatus = (TextView) findViewById(R.id.txtStatus);
		Object obj = getLastNonConfigurationInstance();
		
		ProgressBar bar = (ProgressBar)findViewById(R.id.progressBar);
		bar.setIndeterminate(false);
		bar.setMax(100);		
		
		//stop app timeout
		((CustomSessionApplication) getApplication()).stop();
		
		if (obj == null) {
			_task = new DownloadUpdateV2Task(bar, checksum, version, txtStatus);
			_task.execute(url);			
		} else {
			Object[] arr = (Object[]) obj;			
			_task = (DownloadUpdateV2Task)arr[0];
			
			if (_task != null) {
				_task.setProgressBar(bar);
				_task.setTxtStatus(txtStatus);
			}
			
			_logoutTask = (LogoutTask) arr[1];
			if (_logoutTask != null) {
				ProgressDialog dialog = new ProgressDialog(this);
				dialog.setMessage("Logging out...");
				dialog.setCancelable(false);
				_logoutTask.setDialog(dialog);
			}
		}		
	}
		
	@Override
	public Object onRetainNonConfigurationInstance() {
		_task.setProgressBar(null);		
		_task.setTxtStatus(null);
		return new Object[] { _task, _logoutTask };
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {		
		//getSupportMenuInflater().inflate(R.menu.activity_update, menu);
		return true;
	}
	
	@Override
	public void onBackPressed() {
		exitApp();       
	}	
	
	private void exitApp() {
		new AlertDialog.Builder(new ContextThemeWrapper(this,
				R.style.Theme_Sherlock_Light_Dialog))
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.confirm)
        .setMessage("Keluar aplikasi?")
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {           
            	dialog.dismiss();            	
            	//upload(true);            	
            	//finish();
            	
            	if (_task != null && _task.getStatus() == AsyncTask.Status.RUNNING) {
            		_task.cancel(true);
            	}
            	
            	ProgressDialog pDialog = new ProgressDialog(UpdateActivity.this);
    			pDialog.setMessage("Logging out...");
    			pDialog.setCancelable(false);
    			new LogoutTask(true, false, pDialog, UpdateActivity.this).execute("");
            	//new LogoutTask(true, pDialog).execute("");
            }
        })
        .setNegativeButton(R.string.no, null)
        .show();
	}	
}
